package org.xbl.xchain.sdk.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.parser.Feature;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.serializer.ValueFilter;
import com.google.common.base.CaseFormat;
import org.xbl.xchain.sdk.amino.Codec;
import org.xbl.xchain.sdk.block.BlockInfo;
import org.xbl.xchain.sdk.block.StdTxInfo;
import org.xbl.xchain.sdk.module.wasm.msg.MsgExecuteContract;
import org.xbl.xchain.sdk.module.wasm.msg.MsgExecuteContractV1;
import org.xbl.xchain.sdk.module.wasm.msg.MsgInstantiateContractV1;
import org.xbl.xchain.sdk.module.wasm.msg.MsgMigrateContractV1;

import java.lang.reflect.Field;
import java.util.Base64;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class LongValueFilter implements ValueFilter {
    @Override
    public Object process(Object o, String name, Object value) {
        if (value == null) {
            return value;
        }
        if (value instanceof Long) {
            return value.toString();
        }
        if (value instanceof Integer) {
            try {
                //下划线变小驼峰
                Field field = o.getClass().getDeclaredField(lineToHump(name));
                if (field.getType() == int.class) {
                    return value;
                }
            } catch (NoSuchFieldException e) {
                e.printStackTrace();
                throw new RuntimeException(e);
            }

            return value.toString();
        }
        if (o instanceof MsgInstantiateContractV1 && "init_msg".equals(name)) {
            return JSON.parseObject(new String((byte[]) value), Feature.OrderedField);
        }
        if (o instanceof MsgExecuteContractV1 && "msg".equals(name)) {
            return JSON.parseObject(new String((byte[]) value), Feature.OrderedField);
        }
        if (o instanceof MsgMigrateContractV1 && "msg".equals(name)) {
            return JSON.parseObject(new String((byte[]) value), Feature.OrderedField);
        }
        return value;
    }

    public static String lineToHump(String str) {
        if (!str.contains("_")) {
            return str;
        }
        return CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, str);
    }

    public static void main(String[] args) throws Exception {
        byte[] decode = Base64.getDecoder().decode("YB3zZIoKFH2QPuJNMi4Bm/sS1Luvj74aqAsvEhR9kD7iTTIuAZv7EtS7r4++GqgLLxoEaXRlbSIoeyJjcmVhdGUiOnsidmFsdWUiOiJoYWhhIiwia2V5IjoiaGFoYSJ9fQ==");
        MsgExecuteContract msgExecuteContractV1 = Codec.getAmino().unmarshalBinaryLengthPrefixed(decode, MsgExecuteContract.class);
        System.out.println(1);
    }
}
